package org.lds.message.center.client.autoconfigure;

import lombok.RequiredArgsConstructor;
import org.lds.message.center.client.GrpcClient;
import org.lds.message.center.client.HttpClient;
import org.lds.message.center.client.MessageCenterClient;
import org.lds.message.center.client.constant.ClientConstant;
import org.lds.message.center.client.properties.MessageCenterClientProperties;
import org.lds.message.center.common.Endpoint;
import org.lds.message.center.common.constant.ConnectionTypeConstant;
import org.lds.message.center.service.grpc.MessageCenterServiceGrpc;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Nullable;

@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = ClientConstant.CLIENT_PREFIX, name = "enabled", havingValue = "true")
@EnableConfigurationProperties({MessageCenterClientProperties.class})
@AutoConfigureAfter(MessageCenterGrpcClientAutoConfiguration.class)
public class MessageCenterClientAutoConfiguration {
    private final MessageCenterClientProperties clientProperties;

    @Bean
    public MessageCenterClient messageCenterClient(Endpoint endpoint) {
        return new MessageCenterClient(endpoint);
    }

    @Bean
    @ConditionalOnProperty(prefix = ClientConstant.CLIENT_PREFIX, name = "connection-type", havingValue = ConnectionTypeConstant.HTTP)
    public HttpClient messageCenterHttpEndPoint() {
        return new HttpClient(clientProperties);
    }

    @Bean
    @ConditionalOnProperty(prefix = ClientConstant.CLIENT_PREFIX, name = "connection-type", havingValue = ConnectionTypeConstant.GRPC)
    public GrpcClient messageCenterGrpcEndPoint(@Nullable MessageCenterServiceGrpc.MessageCenterServiceBlockingStub blockStub, @Nullable MessageCenterServiceGrpc.MessageCenterServiceStub stub) {
        return new GrpcClient(blockStub, stub);
    }

}
